import tkinter as tk
from tkinter import ttk

# 假设这些导入模块存在
from src.ragbanben2 import ExperimentDesignApp
from src.xyqm import DOEAnalyzer
from src.bys import BayesianOptimizationGUI
from src.DOE import DOEFullFactorialDesigner


class MainWindow:
    def __init__(self, root):
        self.root = root
        self.root.title("实验优化平台")
        self.root.geometry("1400x900")

        self.main_pane = tk.PanedWindow(self.root, orient=tk.HORIZONTAL)
        self.main_pane.pack(fill=tk.BOTH, expand=True)

        self.doe_analyzer = None

        # 左侧流程导航栏
        self.nav_frame = tk.Frame(self.main_pane, width=200, bg="#f0f0f0")
        self.main_pane.add(self.nav_frame, stretch="never")

        # 工作流程标题
        title_label = tk.Label(self.nav_frame, text="工作流程", font=("Arial", 14, "bold"),
                               bg="#f0f0f0", pady=5)
        title_label.pack(pady=10)

        # 统一按钮样式，使大小一致
        button_width = 15  # 固定按钮宽度
        button_padx = 10  # 按钮左右内边距
        button_pady = 8  # 按钮上下内边距

        # 1.AI因素分析按钮
        self.step1_btn = tk.Button(self.nav_frame, text="1. AI因素分析",
                                   command=self.load_ai_analysis,
                                   width=button_width,
                                   padx=button_padx,
                                   pady=button_pady,
                                   font=("Arial", 10))
        self.step1_btn.pack(pady=5)

        # 2.DOE/贝叶斯优化按钮
        self.step2_btn = tk.Button(self.nav_frame, text="2. DOE/贝叶斯优化",
                                   state=tk.DISABLED,
                                   command=self.load_step2,
                                   width=button_width,
                                   padx=button_padx,
                                   pady=button_pady,
                                   font=("Arial", 10))
        self.step2_btn.pack(pady=5)

        self.step3_btn = None

        # 内容区域容器
        self.content_frame = tk.Frame(self.main_pane)
        self.main_pane.add(self.content_frame, stretch="always")

        # 为每个步骤创建容器（不销毁，只隐藏/显示）
        self.step_frames = {}
        self.create_step_frames()

        # 保存各步骤的应用实例
        self.step_instances = {}

        # 数据保存
        self.factor_count = None
        self.csv_path = None
        self.doe_csv_path = None

    def create_step_frames(self):
        """创建所有步骤的容器框架"""
        for step in ["step1", "step2", "step3"]:
            frame = tk.Frame(self.content_frame)
            self.step_frames[step] = frame
            # 初始都隐藏
            frame.pack_forget()

    def show_step(self, step_name):
        """显示指定步骤，隐藏其他步骤"""
        for frame_name, frame in self.step_frames.items():
            if frame_name == step_name:
                frame.pack(fill=tk.BOTH, expand=True)
            else:
                frame.pack_forget()

    def load_ai_analysis(self):
        """加载第一步：AI因素分析"""
        self.show_step("step1")

        # 如果还没创建过，就创建实例；否则直接显示已有的
        if "ai_app" not in self.step_instances:
            # 清空容器（只在第一次创建时）
            for widget in self.step_frames["step1"].winfo_children():
                widget.destroy()
            self.step_instances["ai_app"] = ExperimentDesignApp(self.step_frames["step1"])
            self.step_instances["ai_app"].on_complete = self.handle_ai_result

    def handle_ai_result(self, factor_count, csv_path):
        self.factor_count = factor_count
        self.csv_path = csv_path
        self.step2_btn.config(state=tk.NORMAL)

        if factor_count <= 3:
            if not self.step3_btn:
                # 保持第三步按钮样式与前两步一致
                self.step3_btn = tk.Button(self.nav_frame, text="3. 响应曲面分析",
                                           state=tk.DISABLED,
                                           command=self.load_response_surface,
                                           width=15,
                                           padx=10,
                                           pady=8,
                                           font=("Arial", 10))
                self.step3_btn.pack(pady=5)
        else:
            if self.step3_btn:
                self.step3_btn.pack_forget()
                self.step3_btn = None

    def load_step2(self):
        """加载第二步：DOE/贝叶斯优化"""
        if self.factor_count is None:
            return

        self.show_step("step2")

        # 根据因子数量创建对应的实例（只创建一次）
        if "step2_instance" not in self.step_instances:
            # 清空容器
            for widget in self.step_frames["step2"].winfo_children():
                widget.destroy()

            if self.factor_count <= 3:
                self.step_instances["step2_instance"] = DOEFullFactorialDesigner(
                    self.step_frames["step2"],
                    csv_path=self.csv_path,
                    factor_count=self.factor_count,
                    on_csv_saved=self.pass_csv_path_to_xyqm
                )
                if self.step3_btn:
                    self.step3_btn.config(state=tk.NORMAL)
            else:
                self.step_instances["step2_instance"] = BayesianOptimizationGUI(
                    self.step_frames["step2"],
                    csv_path=self.csv_path
                )

    def pass_csv_path_to_xyqm(self, path):
        self.doe_csv_path = path
        # 如果第三步已经创建，同步更新数据
        if "response_surface" in self.step_instances:
            self.step_instances["response_surface"].set_csv_path(path)

    def load_response_surface(self):
        """加载第三步：响应曲面分析"""
        self.show_step("step3")

        if "response_surface" not in self.step_instances:
            # 清空容器
            for widget in self.step_frames["step3"].winfo_children():
                widget.destroy()

            self.step_instances["response_surface"] = DOEAnalyzer(self.step_frames["step3"])
            if hasattr(self, 'doe_csv_path'):
                self.step_instances["response_surface"].set_csv_path(self.doe_csv_path)


if __name__ == "__main__":
    root = tk.Tk()
    app = MainWindow(root)
    root.mainloop()
